/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package testing;

import clasificador.genetico.FitnessFunction;
import java.util.ArrayList;

/**
 *
 * @author Simply
 */
public final class Fitness implements FitnessFunction<ArrayList<Character>> {

    private final ArrayList<Character> target;

    private static int minimum(int a, int b, int c) {
        return Math.min(Math.min(a, b), c);
    }

    private static int computeLevenshteinDistance(ArrayList<Character> str1, ArrayList<Character> str2) {
        int[][] distance = new int[str1.size() + 1][str2.size() + 1];

        for (int i = 0; i <= str1.size(); i++) {
            distance[i][0] = i;
        }
        for (int j = 1; j <= str2.size(); j++) {
            distance[0][j] = j;
        }

        for (int i = 1; i <= str1.size(); i++) {
            for (int j = 1; j <= str2.size(); j++) {
                distance[i][j] = minimum(
                        distance[i - 1][j] + 1,
                        distance[i][j - 1] + 1,
                        distance[i - 1][j - 1] + ((str1.get(i - 1) == str2.get(j - 1)) ? 0 : 1));
            }
        }

        return distance[str1.size()][str2.size()];
    }

    public Fitness(ArrayList<Character> target) {
        this.target = target;
    }

    @Override
    public Double f(ArrayList<Character> i) {
        return 1.0 / (1.0 + computeLevenshteinDistance(i, this.target));
    }
}
